const ErrorEnum = require("../utils/errorEnum");

const errorHandler = async (ctx, next) => {
  try {
    await next()
  } catch (err) {
    if (err.name === 'UnauthorizedError' || err.status === 401) {
      ctx.status = 401;
      ctx.body = {
        code: 401,
        type: ErrorEnum[err.status].type,
        message: err.message ||ErrorEnum[err.status].message,
        url: ctx.request.url,
        method: ctx.request.method,
      }
    } else if (ErrorEnum[err.status]) {
      ctx.body = {
        code: err.code,
        type: err.type,
        message: err.message,
        details: err.details,
        url: ctx.request.url,
        method: ctx.request.method,
      }
    } else {
      console.log(17, err);

      ctx.body = {
        code: err.code || 0,
        type: err.type || '未知错误',
        message: err.message || '未知错误',
      }
    }
  }
}

module.exports = errorHandler;
